<template>
  <div>
    <div>
      <div v-if="step === 0">
        <n-form ref="form" :model="model" :rules="rules">
          <n-form-item :label="$t('user.register.username')" path="username">
            <n-input v-model:value="model.username" @keydown.enter.prevent />
          </n-form-item>
          <n-form-item :label="$t('user.register.email')" path="email">
            <n-input v-model:value="model.email" @keydown.enter.prevent />
          </n-form-item>
          <n-form-item :label="$t('user.register.password')" path="password">
            <n-input v-model:value="model.password" type="password" @keydown.enter.prevent />
          </n-form-item>
          <n-form-item :label="$t('user.register.confirm-password')" path="confirmPassword">
            <n-input v-model:value="model.confirmPassword" type="password" @keydown.enter.prevent />
          </n-form-item>
          <n-button :loading="pushing" style="width: 100%" type="primary" @click="submit">
            {{ $t("user.register.title") }}
          </n-button>
          <div class="pt-2 text-center">
            <span class="text-secondary">{{ $t("user.register.agreement.0") }}
              <router-link :to="{ name: 'agreement', query: { page: 'user-must-known' } }">{{
                $t("user.register.agreement.1")
              }}</router-link>
            </span>
          </div>
        </n-form>
      </div>
      <div v-if="step === 1">
        <n-form ref="form" :model="model" :rules="rules">
          <n-form-item :label="$t('user.register.verify-code')" path="verifyCode">
            <n-input v-model:value="model.verifyCode" @keydown.enter.prevent />
          </n-form-item>
          <n-button :loading="pushing" style="width: 100%" type="primary" @click="verify">
            {{ $t("user.register.verify") }}
          </n-button>
        </n-form>
      </div>
    </div>   </div>
</template>

<script setup>
import axiosHttp from "axios";
import { NButton, NForm, NFormItem, NInput, useMessage } from "naive-ui";
import { reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter, RouterLink } from "vue-router";

const { t } = useI18n();
const rules = {
  username: [{ required: true, message: t("user.register.validate.username") }],
  email: [
    { required: true, message: t("user.register.validate.email") },
    {
      validator: (rule, value) => {
        if (
          !new RegExp(
            /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/
          ).test(value)
        ) {
          return new Error(t("user.register.validate.email-invalid"));
        }
      },
    },
  ],
  password: [{ required: true, message: t("user.register.validate.password") }],
  confirmPassword: [
    { required: true, message: t("user.register.validate.confirm-password") },
    {
      validator: (rule, value) => {
        if (value !== model.password) {
          return new Error(
            t("user.register.validate.confirm-password-invalid")
          );
        }
      },
    },
  ],

  verifyCode: [
    { required: true, message: t("user.register.validate.verify-code") },
  ],
};

const router = useRouter();
const axios = axiosHttp.create({ validateStatus: () => true });
const message = useMessage();

const pushing = ref(false);
const form = ref(null);
const step = ref(0);
const model = reactive({
  email: "",
  username: "",
  password: "",
  confirmPassword: "",
  agreement: false,

  verifyCode: "",
});

function submit() {
  form.value?.validate((error) => {
    if (!error) {
      pushing.value = true;
      axios
        .post("/api/management/users", {
          username: model.username,
          password: model.password,
          email: model.email,
        })
        .catch(() => {
          message.error(t("common.message.request-unknown-error"));
          pushing.value = false;
        })
        .then((response) => {
          if (response.status === 201) {
            message.success(t("user.register.messages.require-verify"));
            step.value++;
          } else if (response.data["error"] === "DataError#2") {
            message.warning(t("user.register.messages.used-email"));
          } else if (response.data["error"] === "DataError#1") {
            message.warning(t("user.register.messages.used-username"));
          } else {
            message.error(t("common.messages.request-unknown-error"));
            console.error("Request error: " + response);
          }
          pushing.value = false;
        });
    }
  });
}

function verify() {
  form.value?.validate((error) => {
    if (!error) {
      pushing.value = true;
      axios
        .post(`/api/management/users?verify=${model.verifyCode}`)
        .catch(() => {
          message.error(t("common.messages.request-unknown-error"));
          pushing.value = false;
        })
        .then((response) => {
          if (response.status === 200) {
            message.success(t("user.register.messages.success"));
            router.push({ name: "user.login" });
          } else if (response.data["error"] === "DataError") {
            message.warning(t("user.register.messages.invalid-verify"));
          } else {
            message.error(t("common.messages.request-unknown-error"));
            pushing.value = false;
          }
          pushing.value = false;
        });
    }
  });
}
</script>
